package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    //预约设置中的上传文件
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile multipartFile) {
        //文件上传流程

        try {
            //1.读取文件
            List<String[]> excel = POIUtils.readExcel(multipartFile);
            //2.判断该文件是否为空
            if (excel != null && excel.size() > 0){         //这里是否应该判空如果判空,即使为空,那返回值也是true
                //3.遍历该集合,并将字符串封装进对象                所以加else
                List<OrderSetting> list = new ArrayList<>();
                for (String[] strings : excel) {
                    OrderSetting ord = new OrderSetting(new Date(strings[0]),Integer.parseInt(strings[1]));
                    //4.将对象装进集合
                    list.add(ord);
                }
                //5.调用service方法,将数据写入数据库
                orderSettingService.addOrderSetting(list);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return  new Result(false,MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    @RequestMapping("/findOrderSetting")
    public Result findOrderSetting(String date){
        //注意页面的leftobj需要的日期是天数,而封装的ordersetting类是orderDate,所以这里要封装成map
        try {
            List<Map> list =  orderSettingService.findOrderSetting(date);
            return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.GET_ORDERSETTING_FAIL);
    }

    @RequestMapping("/updateNumber")
    public Result updateNumber(@RequestBody OrderSetting orderSetting){
        try {
            orderSettingService.updateNumber(orderSetting);
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.ORDERSETTING_FAIL);

    }
}
